//默认的工具类
export let digitLength = (num) => {
  const eSplit = num.toString().split(/[eE]/);
  const len = (eSplit[0].split('.')[1] || '').length - (+(eSplit[1] || 0));
  return len > 0 ? len : 0;
}


//精确加法
export let accAdd = (num1, num2) => {
  const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
  return (accMul(num1, baseNum) + accMul(num2, baseNum)) / baseNum;
}

//精确减法
export let accReduce = (num1, num2) => {
  const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
  return (accMul(num1, baseNum) - accMul(num2, baseNum)) / baseNum;
}

//精确乘法
export let accCheng = (num1, num2) => {
  const num1Changed = Number(num1.toString().replace('.', ''));
  const num2Changed = Number(num2.toString().replace('.', ''));
  const baseNum = digitLength(num1) + digitLength(num2);
  return num1Changed * num2Changed / Math.pow(10, baseNum);
}

//精确相除
export let accChu = (num1, num2) => {
  const num1Changed = Number(num1.toString().replace('.', ''));
  const num2Changed = Number(num2.toString().replace('.', ''));
  return accMul((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1)));
}

//将时间戳转换成年月日的形式
export let transTime = (temp) => {
  //确保时间戳为13位
  temp = temp.toString().length == 10 ? temp * 1000 : temp;
  Date.prototype.format = function(format) {
    if (isNaN(this)) return '';
    var o = {
      'm+': this.getMonth() + 1,
      'd+': this.getDate(),
      'h+': this.getHours(),
      'n+': this.getMinutes(),
      's+': this.getSeconds(),
      'S': this.getMilliseconds(),
      'W': ["日", "一", "二", "三", "四", "五", "六"][this.getDay()],
      'q+': Math.floor((this.getMonth() + 3) / 3)
    };
    if (format.indexOf('am/pm') >= 0) {
      format = format.replace('am/pm', (o['h+'] >= 12) ? '下午' : '上午');
      if (o['h+'] >= 12) o['h+'] -= 12;
    }
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    return format;
  }
  let postYear = new Date(temp).format('yyyy');
  let postMonth = new Date(temp).format('mm');
  let postDate = new Date(temp).format('dd');
  let postHours = new Date(temp).format('hh');
  let postMinutes = new Date(temp).format('nn');
  let postMM = new Date(temp).format('ss');
  return postYear + '.' + postMonth + '.' + postDate + ' ' + postHours + ':' + postMinutes
}

//微信版本比较
function compareWechatVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

/**
 * 下载保存一个文件
 */
function downloadFile(obj) {
  let that = this;
  let success = obj.success;
  let fail = obj.fail;
  let id = "";
  let url = obj.url;
  if (obj.id) {
    id = obj.id;
  } else {
    id = url;
  }

  wx.downloadFile({
    url: obj.url,
    success: res => {
      res.id = id;
      success(res);
    },
    fail: function(e) {
      if (fail) {
        fail(e);
      }
    }
  })
}
/**
 * 多文件下载并且保存，强制规定，必须所有文件下载成功才算返回成功
 */
function downloadFiles(obj) {
  // console.info("准备下载。。。");
  let that = this;
  let success = obj.success; //下载成功
  let fail = obj.fail; //下载失败
  let urls = obj.urls; //下载地址 数组，支持多个 url下载 [url1,url2]
  let savedFilePaths = new Map();
  let urlsLength = urls.length; // 有几个url需要下载
  for (let i = 0; i < urlsLength; i++) {
    downloadFile({
      url: urls[i],
      success: function(res) {
        //一个文件下载保存成功
        savedFilePaths.set(res.id, res);
        if (savedFilePaths.size == urlsLength) { //如果所有的url 才算成功
          if (success) {
            success(savedFilePaths);
          }
        }
      },
      fail: function(e) {
        if (fail) {
          fail(e);
        }
      }
    })
  }
}

module.exports = {
  compareWechatVersion: compareWechatVersion,
  downloadFile: downloadFile,
  downloadFiles: downloadFiles
}